package com.cfk.bookmarkdirectory.model;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.fileEditor.FileEditorManager;

import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;

/**
 * author 3156056300@qq.com
 */
public class BookmarkNode extends DefaultMutableTreeNode {
    private String directoryPath;
    private String name;
    private boolean isDirectory;

    public BookmarkNode(String name, String directoryPath, boolean isDirectory) {
        super(name);
        this.name = name;
        this.directoryPath = directoryPath;
        this.isDirectory = isDirectory;
    }

    public String getDirectoryPath() {
        return directoryPath;
    }

    public void setDirectoryPath(String directoryPath) {
        this.directoryPath = directoryPath;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        setUserObject(name);
    }

    public boolean isDirectory() {
        return isDirectory;
    }

    public void navigateToDirectory(Project project) {
        if (directoryPath != null && !directoryPath.isEmpty()) {
            // 获取目录的VirtualFile
            VirtualFile dirFile = LocalFileSystem.getInstance().findFileByIoFile(new File(directoryPath));
            if (dirFile != null && dirFile.isDirectory()) {
                // 获取Project视图工具窗口
                ToolWindow projectWindow = ToolWindowManager.getInstance(project).getToolWindow("Project");
                if (projectWindow != null) {
                    // 激活Project视图
                    projectWindow.show(() -> {
                        // 在Project视图中选中目录
                        ProjectView.getInstance(project).select(null, dirFile, true);
                        // 激活并聚焦到Project视图
                        projectWindow.activate(null);
                    });
                }
            }
        }
    }

    @Override
    public String toString() {
        return name;
    }
}